package cn.edu.ujs.coor.util;

import cn.edu.ujs.coor.model.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JwtUnit {

    private static final String SECRET = "ujs_sso";

    /**
     * 生成jwt令牌
     * @param user
     * @return
     */
    public static String toJwt (User user) {
        String token = "";
        // token过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, 2);
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("id", user.getId())
                    .withClaim("name", user.getName())
                    .withClaim("phone", user.getPhone())
                    .withClaim("email", user.getEmail())
                    .withClaim("dataLevel", user.getDataLevel())
                    .withClaim("organizationId", user.getOrganizationId())
                    .withClaim("expire", String.valueOf(calendar.getTimeInMillis()))
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return token;
    }

    /**
     * 解密token令牌，获取信息
     * @param token
     * @return
     */
    public static Map decode (String token) {
        Map map = new HashMap();
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("auth0")
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            map.put("id", jwt.getClaim("id").asString());
            map.put("name", jwt.getClaim("name").asString());
            map.put("phone", jwt.getClaim("phone").asString());
            map.put("email", jwt.getClaim("email").asString());
            map.put("dataLevel", jwt.getClaim("dataLevel").asString());
            map.put("organizationId", jwt.getClaim("organizationId").asString());
            map.put("expire", jwt.getClaim("expire").asString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
